/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.Finance;

import entity.Credit;
import entity.Customer;
import entity.Invoice;
import entity.Payment;
import entity.PurchaseItem;
import entity.RawMaterialPurchaseOrder;
import entity.Receipt;
import entity.SalesOrder;
import entity.TrackingItem;
import java.io.Serializable;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import managedbean.EmailManager;
import managedbean.UserSessionManagerBean;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import session.stateless.CreditSessionBeanLocal;
import session.stateless.LogSessionBeanLocal;
import session.stateless.RawMaterialPurchaseOrderSessionBeanLocal;
import session.stateless.SalesOrderSessionBeanLocal;

/**
 *
 * @author Wx
 */
@ManagedBean(name = "paymentManagerBean")
@RequestScoped
public class PaymentManagerBean implements Serializable {

    @EJB
    CreditSessionBeanLocal creditSessionBeanLocal;
    @EJB
    SalesOrderSessionBeanLocal salesOrderSessionBeanLocal;
    @EJB
    LogSessionBeanLocal logSessionBeanLocal;
    @EJB
    RawMaterialPurchaseOrderSessionBeanLocal rawMaterialPurchaseOrderSessionBeanLocal;
    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    private List<SalesOrder> salesOrders = new ArrayList<SalesOrder>();
    private List<PurchaseItem> purchaseItems = new ArrayList<PurchaseItem>();
    private SalesOrder selectedSalesOrder;
    private Customer selectedCustomer;
    private PurchaseItem selectedPurchaseItem;
    private RawMaterialPurchaseOrder selectedRawMaterialPurchaseOrder;
    private String loadAddPayment;
    private String loadPayRMPO;
    private int invoiceId;
    //Payment
    private Timestamp paymentDate;
    private Double amountPaid;
    private Invoice invoice;
    private Double balanceUsed;
    private String status;
    private Double amountToPayRMPO;

    /** Creates a new instance of PaymentManagerBean */
    public PaymentManagerBean() {
    }

    public void makePayment(ActionEvent event) {
        try {
            if (amountToPayRMPO > 0) {
                System.out.println("amountToPayRMPO: " + amountToPayRMPO);
                System.out.println("selectedRawMaterialPurchaseOrder.getAmountToPay(): " + selectedRawMaterialPurchaseOrder.getAmountToPay());
                System.out.println((amountToPayRMPO + "").equals(selectedRawMaterialPurchaseOrder.getAmountToPay() + ""));
                if ((amountToPayRMPO + "").equals(selectedRawMaterialPurchaseOrder.getAmountToPay() + "")) {
                    rawMaterialPurchaseOrderSessionBeanLocal.updateRMPO(selectedRawMaterialPurchaseOrder.getId());

                    //redirect to success page
                    ArrayList<String> al = new ArrayList<String>();
                    al.add("Payment record");
                    al.add("You have successfully recorded the payment for RMPO.");
                    al.add("Click on the link to to ");
                    al.add("continue");
                    al.add("Web_Warehouse/searchRawMaterialPurchaseOrders.xhtml");
                    userSessionManagerBean.setSelectedItem(al);

                    logSessionBeanLocal.addLog("Add RMPO payment", "RMPO Payment record created: " + userSessionManagerBean.getUserId(), "payForRMPO.xhtml", userSessionManagerBean.getUserId());

                    FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                            + userSessionManagerBean.getServerName() + ":"
                            + userSessionManagerBean.getServerPort()
                            + "/MerlionERP-war/success.xhtml");
                } else {
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "Inexact amount entered.", ""));
                }
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Payment amount cannot be 0.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @return the status
     */
    public String getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * @return the selectedSalesOrder
     */
    public SalesOrder getSelectedSalesOrder() {
        return selectedSalesOrder;
    }

    /**
     * @param selectedSalesOrder the selectedSalesOrder to set
     */
    public void setSelectedSalesOrder(SalesOrder selectedSalesOrder) {
        this.selectedSalesOrder = selectedSalesOrder;
    }

    /**
     * @return the paymentDate
     */
    public Timestamp getPaymentDate() {
        return paymentDate;
    }

    /**
     * @param paymentDate the paymentDate to set
     */
    public void setPaymentDate(Timestamp paymentDate) {
        this.paymentDate = paymentDate;
    }

    /**
     * @return the amountPaid
     */
    public Double getAmountPaid() {
        return amountPaid;
    }

    /**
     * @param amountPaid the amountPaid to set
     */
    public void setAmountPaid(Double amountPaid) {
        this.amountPaid = amountPaid;
    }

    /**
     * @return the invoice
     */
    public Invoice getInvoice() {
        return invoice;
    }

    /**
     * @param invoice the invoice to set
     */
    public void setInvoice(Invoice invoice) {
        this.invoice = invoice;
    }

    /**
     * @return the balanceUsed
     */
    public Double getBalanceUsed() {
        return balanceUsed;
    }

    /**
     * @param balanceUsed the balanceUsed to set
     */
    public void setBalanceUsed(Double balanceUsed) {
        this.balanceUsed = balanceUsed;
    }

    /**
     * @return the selectedCustomer
     */
    public Customer getSelectedCustomer() {
        return selectedCustomer;
    }

    /**
     * @param selectedCustomer the selectedCustomer to set
     */
    public void setSelectedCustomer(Customer selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    /**
     * @return the loadAddPayment
     */
    public String getLoadAddPayment() {
        selectedCustomer = userSessionManagerBean.getCustomer();

        List<SalesOrder> temp = salesOrderSessionBeanLocal.getSalesOrders("Pending Deliveries and Payments");

        for (SalesOrder so : temp) {
            if (so.getJob().getCustomer().getId() == selectedCustomer.getCustId()) {
                salesOrders.add(so);
            }
        }

        if (userSessionManagerBean.getSelectedSalesOrder2() != null) {
            selectedSalesOrder = userSessionManagerBean.getSelectedSalesOrder2();
        }

        if (userSessionManagerBean.getPurchaseItems() != null) {
            purchaseItems = userSessionManagerBean.getPurchaseItems();
        }

        invoiceId = 0;
        amountPaid = 0.0;
        balanceUsed = 0.0;

        return null;
    }

    /**
     * @param loadAddPayment the loadAddPayment to set
     */
    public void setLoadAddPayment(String loadAddPayment) {
        this.loadAddPayment = loadAddPayment;
    }

    /**
     * @return the salesOrders
     */
    public List<SalesOrder> getSalesOrders() {
        return salesOrders;
    }

    /**
     * @param salesOrders the salesOrders to set
     */
    public void setSalesOrders(List<SalesOrder> salesOrders) {
        this.salesOrders = salesOrders;
    }

    public void onRowSelect(SelectEvent event) {
        if (event.getComponent().getId().equals("salesOrders")) { //if salesOrders datatable called
            try { //reload page on select of salesOrders
                purchaseItems = selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems();

                userSessionManagerBean.setPurchaseItems(purchaseItems);
                userSessionManagerBean.setSelectedSalesOrder2(selectedSalesOrder);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Finance/addPayment.xhtml");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public void onRowUnselect(UnselectEvent event) {
        if (event.getComponent().getId().equals("salesOrders")) { //if salesOrders datatable called
            selectedSalesOrder = null;
            purchaseItems = null;
            selectedPurchaseItem = null;
        } else { //if purchaseItems datatable called
            selectedPurchaseItem = null;
        }
    }

    public void addPayment(ActionEvent event) {
        try {
            if (selectedPurchaseItem != null) { //if an item to pay for was selected
                if (!selectedPurchaseItem.getStatus().equals("Fully Paid")) {
                    if (!selectedPurchaseItem.getStatus().equals("Cancelled")) {
                        selectedSalesOrder = userSessionManagerBean.getSelectedSalesOrder2();

                        if (selectedPurchaseItem.getStatus().equals("Pending Final Payment")) {
                            invoice = creditSessionBeanLocal.getInvoice(selectedPurchaseItem.getId(), "Pending Payment", "Final Payment");
                        } else if (selectedPurchaseItem.getStatus().equals("Pending Advance Payment")) {
                            invoice = creditSessionBeanLocal.getInvoice(selectedPurchaseItem.getId(), "Pending Payment", "Advance Payment");
                        }

                        if (invoice != null) { //if there are invoices for the selected purchase item
                            if (invoiceId == invoice.getId()) { //if invoiceId entered matches invoiceId for the selectedPurchaseItem
                                Credit credit = selectedCustomer.getCredit();

                                if (credit.getBalance() >= balanceUsed) { //balance to use falls within customer's currently available balance 
                                    if (((amountPaid + balanceUsed) + "").equals((invoice.getAmount() + ""))) { //if amountPaid is equal to the amount that was invoiced
                                        if (invoice.getType().equals("Advance Payment")) { //if payment is made for advance payment
                                            status = "Cash in Advance";
                                        } else { //if payment is made for final payment
                                            status = "Final Payment";
                                        }

                                        balanceUsed = round(balanceUsed, 2);
                                        amountPaid = round(amountPaid, 2);
                                        amountPaid += balanceUsed;
                                        amountPaid = round(amountPaid, 2);

                                        //add the payment record
                                        creditSessionBeanLocal.addPayment(invoice.getId(), amountPaid, balanceUsed, status);

                                        //get the payment record that was newly added
                                        Payment payment = creditSessionBeanLocal.getPayment(invoice.getId());

                                        //recalculate credit information - start
                                        //check if payment made within 30 days of invoice date
                                        Calendar cal1 = Calendar.getInstance();
                                        Calendar cal2 = Calendar.getInstance(); //current time

                                        cal1.setTime(invoice.getInvoiceDate());
                                        cal1.add(cal1.DAY_OF_YEAR, 30); //add 30 days to invoice date

                                        Double balance = credit.getBalance();
                                        if (cal2.compareTo(cal1) < 0) { //payment made within 30 days of invoice date
                                            if (balanceUsed <= 0) { //if using balance, no discount offered
                                                //give a 1% discount off invoice amount and credit into balance
                                                balance += round(invoice.getAmount() * 0.01, 2);
                                            }

                                            balance = round(balance, 2);
                                            credit.setBalance(balance);

                                            Integer paymentsPaidLessThan30 = credit.getPaymentsPaidLessThan30();
                                            paymentsPaidLessThan30++; //increment payments paid in less than 30 days

                                            credit.setPaymentsPaidLessThan30(paymentsPaidLessThan30);
                                        } else { //payment made 30 days after invoice date
                                            cal1.setTime(invoice.getInvoiceDate());
                                            cal1.add(cal1.DAY_OF_YEAR, 60);

                                            if (cal2.compareTo(cal1) < 0) { //payment made within 30 to 59 days
                                                Integer paymentsPaidLate30to59 = credit.getPaymentsPaidLate30to59();
                                                paymentsPaidLate30to59++; //increment payments paid within 30 to 59 days

                                                credit.setPaymentsPaidLate30to59(paymentsPaidLate30to59);
                                            } else { //payment made 60 days after invoice date
                                                cal1.setTime(invoice.getInvoiceDate());
                                                cal1.add(cal1.DAY_OF_YEAR, 90);

                                                if (cal2.compareTo(cal1) < 0) { //payment made within 60 to 89 days
                                                    Integer paymentsPaidLate30to59 = credit.getPaymentsPaidLate30to59();
                                                    paymentsPaidLate30to59++; //increment payments paid within 60 to 89 days

                                                    credit.setPaymentsPaidLate30to59(paymentsPaidLate30to59);
                                                } else { //payments made after 90 days
                                                    Integer paymentsPaidLaterThan90 = credit.getPaymentsPaidLaterThan90();
                                                    paymentsPaidLaterThan90++; //increment payments paid after 90 days

                                                    credit.setPaymentsPaidLaterThan90(paymentsPaidLaterThan90);
                                                }
                                            }
                                        }

                                        Integer totalPayments = credit.getTotalPayments();
                                        totalPayments++; //increment total payments made by customer

                                        credit.setTotalPayments(totalPayments);

                                        //recalculate paymentScore - start
                                        double num2 = credit.getPaymentsPaidLessThan30();
                                        double num3 = credit.getPaymentsPaidLate30to59();
                                        double num4 = credit.getPaymentsPaidLate60to89();
                                        double num5 = credit.getPaymentsPaidLaterThan90();

                                        double num31 = (num3 / totalPayments) * 20;
                                        double num41 = (num4 / totalPayments) * 30;
                                        double num51 = (num5 / totalPayments) * 50;

                                        Double paymentScore = 100 - num31 - num41 - num51;
                                        paymentScore = 0.4 * paymentScore;
                                        paymentScore = round(paymentScore, 2);
                                        //recalculate paymentScore - end

                                        //recalculate outstanding score - start
                                        Double deposit = credit.getDeposit();
                                        Double accountsPayable = credit.getAccountsPayable();
                                        Double outstandingScore = credit.getOutstandingScore();
                                        Double creditScore = credit.getCreditScore();
                                        Double totalAmount = credit.getTotalAmount();

                                        deposit += payment.getAmountPaid();
                                        deposit = round(deposit, 2);

                                        accountsPayable -= payment.getAmountPaid();
                                        accountsPayable = round(accountsPayable, 2);

                                        if (accountsPayable < 0) {
                                            accountsPayable = round(0.00, 2);
                                        }

                                        if (accountsPayable > totalAmount) {
                                            outstandingScore = round(0.00, 2);
                                        } else {
                                            double num1 = (accountsPayable / totalAmount) * 100;
                                            num1 = 100 - num1;

                                            outstandingScore = 0.4 * num1;
                                            outstandingScore = round(outstandingScore, 2);
                                        }
                                        //recalculate outstanding score - end

                                        if (balanceUsed > 0) { //if balance account was used
                                            balance -= balanceUsed;
                                            balance = round(balance, 2);
                                        }

                                        if (balance < 0) {
                                            balance = round(0.00, 2);
                                        }

                                        creditScore -= credit.getOutstandingScore();
                                        creditScore += outstandingScore;
                                        creditScore -= credit.getPaymentScore();
                                        creditScore += paymentScore;

                                        creditScore = round(creditScore, 2);

                                        credit.setBalance(balance);
                                        credit.setPaymentScore(paymentScore);
                                        credit.setAccountsPayable(accountsPayable);
                                        credit.setCreditScore(creditScore);
                                        credit.setOutstandingScore(outstandingScore);
                                        credit.setDeposit(deposit);
                                        
                                        creditSessionBeanLocal.updateCredit(credit.getId(), credit); //update credit
                                        //recalculate credit information - end

                                        //update selectedPurchaseItem's status
                                        double outstandingAmount = 0.0;
                                        String purchaseItemStatus = "Pending for Shipping"; //purchase item will be pending for shipping

                                        if (status.equals("Cash in Advance")) { //if payment is an advance payment
                                            if (selectedSalesOrder.getJob().getPurchaseOrder().getCreditRate() > 0) { //if PO has credit
                                                double outstanding = selectedSalesOrder.getJob().getPurchaseOrder().getCreditRate() / 100;
                                                outstandingAmount = outstanding * selectedPurchaseItem.getSubTotal(); //recalculate outstanding amount

                                                outstandingAmount = round(outstandingAmount, 2);
                                            }

                                            purchaseItemStatus = "Pending for Shipping"; //purchase item will be pending for shipping
                                        } else if (status.equals("Final Payment")) {
                                            purchaseItemStatus = "Fully Paid"; //purchase item has been fully paid for
                                        }

                                        creditSessionBeanLocal.updatePurchaseItem(selectedPurchaseItem.getId(), outstandingAmount, purchaseItemStatus);

                                        //retrieve sales order with updated purchaseItems
                                        selectedSalesOrder = salesOrderSessionBeanLocal.getSalesOrder(selectedSalesOrder.getId());

                                        Boolean isAllPaid = true;
                                        //loop through all purchase items of the order
                                        for (PurchaseItem pi : selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems()) {
                                            if (!pi.getStatus().equals("Fully Paid") && !pi.getStatus().equals("Cancelled")) {
                                                isAllPaid = false; //there is still one purchase item that is not fully paid for
                                                break;
                                            }
                                        }

                                        //update invoice status
                                        creditSessionBeanLocal.updateInvoice(invoice.getId(), "Paid");

                                        NumberFormat nf = NumberFormat.getCurrencyInstance();
                                        TrackingItem ti = new TrackingItem();
                                        ti.setDescription("Payment of " + nf.format(payment.getAmountPaid()) + " made for sales order id " + selectedSalesOrder.getId() + " for purchase item id " + selectedPurchaseItem.getId() + ".");

                                        //add ti to sales order's tracking items
                                        salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), ti);

                                        //add receipt for the payment
                                        Receipt receipt;
                                        if (isAllPaid) { //if all purchase items have been fully paid for
                                            //add receipt for for the whole order
                                            creditSessionBeanLocal.addReceipt(payment.getId(), selectedSalesOrder.getJob().getPurchaseOrder().getTotalAmount(), "Paid");

                                            receipt = creditSessionBeanLocal.getReceipt(payment.getId());

                                            //update sales order status
                                            salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), "Completed");

                                            ti = new TrackingItem();
                                            ti.setDescription("Sales Order Fully Paid For and Completed");

                                            //add ti to sales order's tracking items
                                            salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), ti);

                                            //send the receipt to customer
                                            sendReceipt(selectedSalesOrder, selectedPurchaseItem, selectedCustomer, receipt, invoice, 1);
                                        } else { //if there is still one purchase item that is not fully paid for
                                            //add receipt for the purchase item
                                            creditSessionBeanLocal.addReceipt(payment.getId(), payment.getAmountPaid(), "Paid");

                                            receipt = creditSessionBeanLocal.getReceipt(payment.getId());

                                            //send the receipt to customer
                                            sendReceipt(selectedSalesOrder, selectedPurchaseItem, selectedCustomer, receipt, invoice, 2);
                                        }

                                        //clear session variables
                                        userSessionManagerBean.setSelectedSalesOrder2(null);
                                        userSessionManagerBean.setPurchaseItems(null);

                                        //redirect to success page
                                        ArrayList<String> al = new ArrayList<String>();
                                        al.add("Payment record");
                                        al.add("You have successfully recorded the payment.");
                                        al.add("Click on the link to to ");
                                        al.add("continue");
                                        al.add("Web_Sales/searchCustomer.xhtml?request=addPayment");
                                        userSessionManagerBean.setSelectedItem(al);

                                        logSessionBeanLocal.addLog("Add payment", "Payment record created: " + userSessionManagerBean.getUserId(), "addPayment.xhtml", userSessionManagerBean.getUserId());

                                        FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                                                + userSessionManagerBean.getServerName() + ":"
                                                + userSessionManagerBean.getServerPort()
                                                + "/MerlionERP-war/success.xhtml");
                                    } else { //if amountPaid is not equal to the amount that was invoiced
                                        FacesContext.getCurrentInstance().addMessage(null,
                                                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Inexact amount entered or amount paid and balance used does not tally with amount to pay.", ""));
                                    }
                                } else { //balance to use exceeds customer's currently available balance
                                    FacesContext.getCurrentInstance().addMessage(null,
                                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "Balance to use exceeds customer's currently available balance.", ""));
                                }
                            } else { //if invoiceId entered does not match invoiceId for the selectedPurchaseItem
                                FacesContext.getCurrentInstance().addMessage(null,
                                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid invoice id entered.", ""));
                            }
                        } else { //if there is no invoice pending for the item
                            FacesContext.getCurrentInstance().addMessage(null,
                                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "There is currently no invoice for this item.", ""));
                        }
                    } else {
                        FacesContext.getCurrentInstance().addMessage(null,
                                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Item has already been cancelled.", ""));
                    }
                } else {
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "Item has already been fully paid for.", ""));
                }
            } else { //if an item to pay for was not selected
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select an item to pay for before continuing.", ""));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void sendReceipt(SalesOrder so, PurchaseItem pi, Customer customer, Receipt r, Invoice i, int type) {
        String msg = "Dear " + customer.getCompany() + ",\n\n";

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

        NumberFormat nf = NumberFormat.getCurrencyInstance();

        msg += "Payment Date: " + sdf.format(r.getPayment().getPaymentDate()) + "\n";
        msg += "Payment Amount: " + nf.format(r.getPayment().getAmountPaid()) + "\n";
        msg += "Invoice No.: " + i.getId() + "\n";
        msg += "Invoice Date: " + sdf.format(i.getInvoiceDate()) + "\n";
        msg += "Purchase Item: " + pi.getProduct().getName() + "\n";
        msg += "Purchase Quantity: " + pi.getQuantity() + "\n";

        String subject = "";
        String remarks = "";
        if (type == 1) { //to send receipt for the whole order
            subject = "Receipt for Sales Order";

            remarks += "Remarks: Your sales order has been completed and fully paid for.\n\n";
        } else { //to send receipt for the purchase item
            subject = "Receipt for Payment";

            remarks += "Remarks: Receipt for payment for single purchase item.\n\n";
        }

        msg += remarks;
        msg += "Regards,\nMerlion Food Limited";

        String sender = "mf.merlionerp@gmail.com";
        String receiver = customer.getEmail();
        String password = "merlionfood";

        System.out.println("Sending receipt to " + receiver + "...");

        EmailManager em = new EmailManager();
        em.sendEmail(subject, msg, sender, receiver, password);
    }

    public double round(double valueToRound, int numberOfDecimalPlaces) {
        double multiplicationFactor = Math.pow(10, numberOfDecimalPlaces);
        double interestedInZeroDPs = valueToRound * multiplicationFactor;

        return Math.round(interestedInZeroDPs) / multiplicationFactor;
    }

    /**
     * @return the selectedPurchaseItem
     */
    public PurchaseItem getSelectedPurchaseItem() {
        return selectedPurchaseItem;
    }

    /**
     * @param selectedPurchaseItem the selectedPurchaseItem to set
     */
    public void setSelectedPurchaseItem(PurchaseItem selectedPurchaseItem) {
        this.selectedPurchaseItem = selectedPurchaseItem;
    }

    /**
     * @return the purchaseItems
     */
    public List<PurchaseItem> getPurchaseItems() {
        return purchaseItems;
    }

    /**
     * @param purchaseItems the purchaseItems to set
     */
    public void setPurchaseItems(List<PurchaseItem> purchaseItems) {
        this.purchaseItems = purchaseItems;
    }

    /**
     * @return the invoiceId
     */
    public int getInvoiceId() {
        return invoiceId;
    }

    /**
     * @param invoiceId the invoiceId to set
     */
    public void setInvoiceId(int invoiceId) {
        this.invoiceId = invoiceId;
    }

    /**
     * @return the selectedRawMaterialPurchaseOrder
     */
    public RawMaterialPurchaseOrder getSelectedRawMaterialPurchaseOrder() {
        return selectedRawMaterialPurchaseOrder;
    }

    /**
     * @param selectedRawMaterialPurchaseOrder the selectedRawMaterialPurchaseOrder to set
     */
    public void setSelectedRawMaterialPurchaseOrder(RawMaterialPurchaseOrder selectedRawMaterialPurchaseOrder) {
        this.selectedRawMaterialPurchaseOrder = selectedRawMaterialPurchaseOrder;
    }

    /**
     * @return the amountToPayRMPO
     */
    public Double getAmountToPayRMPO() {
        return amountToPayRMPO;
    }

    /**
     * @param amountToPayRMPO the amountToPayRMPO to set
     */
    public void setAmountToPayRMPO(Double amountToPayRMPO) {
        this.amountToPayRMPO = amountToPayRMPO;
    }

    /**
     * @return the loadPayRMPO
     */
    public String getLoadPayRMPO() {
        selectedRawMaterialPurchaseOrder = userSessionManagerBean.getSelectedRawMaterialPurchaseOrder();

        return null;
    }

    /**
     * @param loadPayRMPO the loadPayRMPO to set
     */
    public void setLoadPayRMPO(String loadPayRMPO) {
        this.loadPayRMPO = loadPayRMPO;
    }
}
